package com.fiona.core.handle.impl;

import java.lang.reflect.Method;

import com.fiona.core.handle.Handler;
import com.fiona.core.load.LoadHelper;
import com.fiona.core.message.RpcRequest;
import com.fiona.core.message.RpcResponse;
import com.fiona.core.message.enums.RpcResponseCodeEnum;
import com.fiona.core.model.FionaMappingModel;
import com.fiona.core.remoting.model.FionaApiServiceObj;
import com.fiona.core.remoting.model.Service;

/**
 *
 * 请求处理者，提供解组请求、编组响应等操作
 * 
 * @author huacongnan
 * @date 2021/3/26
 */
public class RequestHandler implements Handler {

	@Override
	public Object handle(Object obj) throws Throwable {
		RpcRequest request = null;
		RpcResponse response = null;
		if (obj instanceof RpcRequest) {
			request = (RpcRequest) obj;
			Service service = FionaApiServiceObj.getService("");

			if (service == null) {
				response = RpcResponse.fail(RpcResponseCodeEnum.SERVICE_CAN_NOT_BE_FOUND);
			} else {
				try {
					// 反射调用对应的方法过程
					// Method method = so.getClazz().getMethod(request.getMethodName(),
					// request.getParamTypes());
					FionaMappingModel fionaMappingModel = LoadHelper.getFionaApiObjectMap().get("");
					Method method = fionaMappingModel.getExeMethod();
					Object returnValue = method.invoke(service.getObj(), request.getParameters());
					response = RpcResponse.success(returnValue, request.getRequestId());
				} catch (Exception e) {
					response = RpcResponse.fail(RpcResponseCodeEnum.FAIL);
				}
			}
		}

		return response;
	}

}
